package com.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.exam.constants.Constant;
import com.exam.exceptions.BizIllegalException;
import com.exam.pojo.domain.QuestionDiscuss;
import com.exam.pojo.domain.User;
import com.exam.pojo.page.PageResult;
import com.exam.pojo.vo.QuestionDiscussVO;
import com.exam.service.IQuestionDiscussService;
import com.exam.utils.CollUtils;
import com.exam.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class QuestionDiscussImpl implements IQuestionDiscussService {

    private final StringRedisTemplate redisTemplate;
    private final MongoTemplate mongoTemplate;
    @Override
    public void add(QuestionDiscuss dto) {
        //每日一分钟内只能提交一次
        String key = StringUtils.format(Constant.discussKey,dto.getUuid(),dto.getQuestionId());
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", Duration.ofSeconds(120));
        if (flag){
            dto.setCreateTime(LocalDateTime.now());
            mongoTemplate.insert(dto);
        }else{
            throw new BizIllegalException(HttpStatus.TOO_MANY_REQUESTS.value(),"Too Many Requests");
        }
    }

    @Override
    public PageResult<QuestionDiscussVO> queryByQuestionId(Long questionId, Integer page, Integer size) {
        Query query = Query.query(Criteria.where("questionId").is(questionId).and("status").is(1));

        long total = mongoTemplate.count(query, QuestionDiscuss.class);

        query.with(Sort.by(Sort.Direction.DESC,"createTime"))
                .skip((page-1)*size)
                .limit(size);

        List<QuestionDiscuss> questionDiscusses = mongoTemplate.find(query, QuestionDiscuss.class);
        if(CollUtils.isNotEmpty(questionDiscusses)){
            List<QuestionDiscussVO> voList = new ArrayList<>();
            List<String> uuidList = CollUtils.getFieldValues(questionDiscusses, "uuid", String.class);
            if(CollUtils.isNotEmpty(uuidList)){
                //查询用户数据
                List<User> userList = mongoTemplate.find(Query.query(Criteria.where("id").in(uuidList)), User.class);
                //list-->map
                Map<String, User> userMap = CollUtils.fieldValueMap(userList, "id");
                //组装数据
                for (QuestionDiscuss questionDiscuss : questionDiscusses) {
                    QuestionDiscussVO vo = BeanUtil.toBean(questionDiscuss, QuestionDiscussVO.class);
                    if (vo.getAnonymous() == 1){
                        vo.setNickname("anonyamousnickname");
                        vo.setHeadImg("105");
                    }else{
                        User user = userMap.getOrDefault(questionDiscuss.getUuid(), User.defaultUser());
                        vo.setNickname(user.getNickname());
                        vo.setHeadImg(user.getHeadImg());
                    }
                    voList.add(vo);
                }
                return PageResult.of(size,total,voList);
            }
        }
        return PageResult.empty();
    }

}
